package com.czf.testmodule.oss.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.czf.testmodule.oss.entity.OssResult;
import com.czf.testmodule.oss.service.IOssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author zfChen
 * @create 2022/5/19 15:48
 */
@Service
@Slf4j
public class OssServiceImpl implements IOssService {

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Autowired
    private OSSClient ossClient;

    @Override
    public OssResult upload(MultipartFile file) {
        String fileSize = "";
        long fileByte = file.getSize();
        if (fileByte < 1024) {
            fileSize = fileByte+"字节";
        } else {
            long fileKB = fileByte / 1024;
            if (fileKB < 1024) {
                fileSize = fileKB+"KB";
            } else {
                long fileMB = fileKB / 1024;
                fileSize = fileMB+"MB";
            }
        }

        try {
            return upload(file.getInputStream(), file.getOriginalFilename(),fileSize);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("error:{}", JSON.toJSONString(e));
        }
        return null;
    }

    @Override
    public OssResult upload(InputStream inputStream, String name,String size) {
        String fileName = getBucketName(name);
        PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream);
        log.info("上传结果:{}",JSON.toJSONString(result));
        if (ObjectUtils.isEmpty(result)) {
            return null;
        }
        String path = formatPath(fileName);
        String markdownPath = markdownFormat(path,fileName);
        OssResult ossResult = new OssResult();
        ossResult.setFileName(fileName);
        ossResult.setFileSize(size);
        ossResult.setFilePath(path);
        ossResult.setMarkdownPath(markdownPath);
        return ossResult;
    }

    @Override
    public ResponseEntity<Object> download(String fileName) {
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        //这里定制下载文件的名称
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/octet-stream"))//以二进制流的形式返回
                .body(new InputStreamResource(ossObject.getObjectContent()));
    }


    private String getBucketName(String name){
        String[] split = name.split("\\.");
        String fileName = "";
        String fileFormat = "";
        if (split.length == 2){
             fileName = split[0];
             fileFormat = split[1];
        } else {
             fileFormat = split[split.length-1];
            for (int i = 0; i < split.length-1; i++) {
                fileName += split[i]+".";
            }
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        return fileName+"-"+System.currentTimeMillis()+"."+fileFormat;
    }

    private String formatPath(String name){
        return "https://"  +bucketName+"."+ ossClient.getEndpoint().getHost() + "/" + name;
    }

    private String markdownFormat(String path,String name){
        return "!["+name+"]"+"("+path+")";
    }

}


